package net.sxnic.normal.util;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.persistence.EntityNotFoundException;

import net.sxinfo.core.entity.EntityAlreadyExistsException;
import net.sxnic.comm.CommConstant;
import net.sxnic.item.mdata.MdataManager;
import net.sxnic.ugr.dept.Dept;
import net.sxnic.ugr.dept.DeptManager;
import net.sxnic.ugr.group.Group;
import net.sxnic.ugr.group.GroupManager;
import net.sxnic.ugr.permission.PermissionManager;
import net.sxnic.ugr.resource.ResourceManager;
import net.sxnic.ugr.role.Role;
import net.sxnic.ugr.security.AuthorizationManager;
import net.sxnic.ugr.user.User;
import net.sxnic.ugr.user.UserManager;
import net.sxnic.ugr.website.WebsiteManager;
import net.sxnic.workflow.task.TaskManager;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 用户组角色导入工具类 user.iint1 短信有效条数 user.str1 短号码 用户识别码
 * 
 * @author yfsun
 * 
 */
public class UgrImportUtils {

	private static final Log log = LogFactory.getLog(UgrImportUtils.class);

	/**
	 * 初始化admin用户和一个test1用户
	 * 因为User加入了dept所以admin用户必须在dept初始化之后进行，而且deptCode=999
	 * 
	 * @param userManager
	 * @param authManager
	 * @throws EntityAlreadyExistsException
	 */
	public static void initAdminUser(UserManager userManager,DeptManager deptManager,
			AuthorizationManager authManager)
			throws Exception {

		User user = new User();
		Role role = new Role();
		Dept dept = deptManager.findByCode("999");
		if(dept==null){
			throw new Exception("===在初始化管理员admin用户之前，必须先进行部门Dept的初始化=====");
		}

		if (userManager.getUserByUsername("admin") == null) {
			role= authManager.getRole(Role.SYSTEM_ADMIN);
			if(role==null){
				role = new Role();
				role.setRole(Role.SYSTEM_ADMIN);
				role.setName("系统管理员");
				authManager.createRole(role);
			}			

			user = new User();
			user.setFullname("系统管理员");
			user.setUsername("admin");
			user.setPassword(DigestUtils.md5Hex("admin"));
			
			userManager.save(user);

			authManager.grantRole(user, Role.SYSTEM_ADMIN);
		}
	}

	/**
	 * 初始化非申报用户的用户，组，角色,权限，资源信息
	 * 
	 * @param authorizationManager
	 * @param groupManager
	 * @param userManager
	 * @param permissionManager
	 * @param resourceManager
	 * @param lines
	 * @throws EntityAlreadyExistsException
	 */
	public static void importUserRoleGroup(
			AuthorizationManager authorizationManager,
			GroupManager groupManager, UserManager userManager,
			PermissionManager permissionManager,
			ResourceManager resourceManager, DeptManager deptManager,
			WebsiteManager wsManager,MdataManager mdManager,TaskManager taskManager, String filepath)
			throws EntityAlreadyExistsException, IOException {

		String type = "";
		String[] r = null;

		// Permission p = null;
		// Resource res = null;
		Role role = null;
		Group group = null;
		// User user = null;

		File file = new File(filepath);
		List<String> lines = FileUtils.readLines(file, "utf-8");

		for (String line : lines) {
			if (StringUtils.isBlank(line)
					|| line.startsWith(CommConstant.TXT_IGNORE_CHAR)) {
				continue;
			}

			if (line.startsWith("U") || line.startsWith("R")
					|| line.startsWith("G")) {
				type = line.trim();

				continue;
			}

			r = StringUtils.split(line, ",");

			// 角色
			if ("R".equals(type)) {
				role = authorizationManager.getRole(r[0].trim());

				if (role == null) {
					role = new Role();
					role.setName(r[1].trim());
					role.setRole(r[0].trim());

					authorizationManager.createRole(role);
					log.debug("role created success, role is : "
							+ role.getRole());
				} else {
					role.setName(r[1].trim());
					authorizationManager.updateRole(role);
					log.debug("role update success, role is : "
							+ role.getRole());
				}

				// 把role对应的menu 全删了
				role.getMenus().clear();
				authorizationManager.updateRole(role);

				String[] mnames = StringUtils.split(r[2], "&");
				// 重新把新的menu加到role
				authorizationManager.addRoleMenu(r[0], mnames);

				continue;
			}

			// 组
			if ("G".equals(type)) {
				group = groupManager.findByUnique("group", r[0].trim());

				if (group == null) {
					group = new Group(r[0].trim(), r[1].trim());

					groupManager.save(group);
					log.debug("group created success, group is : "
							+ group.getName());
				} else {
					group.setName(r[1].trim());
					groupManager.update(group);
					log.debug("group update success, group is : "
							+ group.getName());
				}

				continue;
			}

			// 组、角色
			if ("R-G".equals(type)) {
				group = groupManager.findByUnique("group", r[1].trim());
				role = authorizationManager.getRole(r[0].trim());

				if (group == null || role == null) {
					log.warn(" group is null or role is null! can't import anything");
					continue;
				} else if (authorizationManager.isGroupInRole(group,
						role.getRole())) {
					log.debug("group already granted role, group is : "
							+ group.getName() + ", role is : " + role.getRole());
					continue;
				} else {
					authorizationManager.grantRole(group, role);
					log.debug("group granted role success, group is : "
							+ group.getName() + ", role is : " + role.getRole());
					continue;
				}
			}

			// 用户
			if ("U".equals(type)) {
				importUsers(userManager, authorizationManager, deptManager,wsManager,
						new String[] { line });
				continue;
			}
		}

		log.debug("===importUserRoleGroup success===");
	}

	/**
	 * 导入用户信息，验证重名数据，如果有此username的数据，则直接update表中的对应的数据
	 * 
	 * @param userManager
	 * @param authManager
	 * @param lines
	 * @throws EntityAlreadyExistsException
	 */
	public static void importUsers(UserManager userManager,
			AuthorizationManager authManager, DeptManager deptManager,WebsiteManager wsManager,
			String[] lines) throws EntityAlreadyExistsException,
			EntityNotFoundException {

		String[] roles = null;
		String[] groups = null;
		Role role = null;
		Group group = null;
		String role_s = "";
		String group_s = "";
		Dept d = null;
		User u = null;

		Set<String> userNameSet = new HashSet<String>();

		for (String line : lines) {
			log.debug("line = " + line);
			if (StringUtils.isBlank(line)
					|| line.startsWith(CommConstant.TXT_IGNORE_CHAR)) {

				continue;
			}

			String[] m = line.split(",");

			// 验证是否有重复用户名
			if (userNameSet.contains(m[0].trim())) {
				throw new EntityNotFoundException("====用户名重复==" + m[0]);
			}
			userNameSet.add(m[0].trim());

			//gcjszx0010,123456,山西省科学技术厅,staff,001000,001,
			// 根据userName，查询表中是否有此userName的用户信息，如果有则update，否则create
			u = userManager.getUserByUsername(m[0].trim());
			if (u != null) {
				u.setUsername(m[0].trim());
				u.setPassword(DigestUtils.md5Hex(m[1].trim()));
				u.setFullname(m[2].trim());				
				u.setUserOrder(Integer.parseInt(m[4].trim()));
				//部门，单位
				d = deptManager.findByCode(m[5].trim());
				u.setDept(d);

				u.getRoles().clear();
				u.getGroups().clear();

				userManager.update(u);
				log.debug("update user success. username = " + u.getUsername());
			} else {
				u = new User();
				u.setUsername(m[0].trim());
				u.setPassword(DigestUtils.md5Hex(m[1].trim()));	
				u.setFullname(m[2].trim());				
				u.setUserOrder(Integer.parseInt(m[4].trim()));
				d = deptManager.findByCode(m[5].trim());
				u.setDept(d);
				userManager.save(u);
				log.debug("create user success. username = " + u.getUsername());
			}

			// 重新设定User 对应的Role 和Group
			role_s = m[3].trim();
			if (!"admin".equals(u.getUsername())) {
				if (!StringUtils.contains(role_s, "allRole")) {
					if (StringUtils.isBlank(role_s)) {
						role_s = "allRole";
					} else {
						role_s = role_s + "/allRole";
					}
				}
				if (!StringUtils.contains(role_s, "staff")) {
					if (StringUtils.isBlank(role_s)) {
						role_s = "staff";
					} else {
						role_s = role_s + "/staff";
					}
				}
			}

			roles = StringUtils.split(role_s, "/");
			for (String r : roles) {
				role = authManager.getRole(r);
				if (role == null) {
					log.error("====User def Role error==u=" + u.getUsername()
							+ "===r=" + r);
					throw new EntityNotFoundException(
							"====User def Role error==u=" + u.getUsername()
									+ "===r=" + r);
				} else {
					u.addRole(role);
				}
			}

			//group和role是成对出现，group=role_g
			group_s = m[3].trim()+"_g";
			groups = StringUtils.split(group_s, "/");
			for (String g : groups) {
				group = authManager.getGroup(g);
				if (group == null) {
					log.error("====User def Group error==u=" + u.getUsername()
							+ "===g=" + g);
					throw new EntityNotFoundException(
							"====User def Group error==u=" + u.getUsername()
									+ "===g=" + g);
				} else {
					u.getGroups().add(group);
				}
			}

			log.debug("===设定User的Role和Group成功===u=" + m[0] + "==r==" + m[3]
					+ "==g==" + m[3]+"_g");			
			
			if (d != null) {
				d.getUsers().add(u);
				deptManager.update(d);
				log.debug("===设定User所属Dept成功===u=" + m[0] + "==d=="
						+ d.getName());
			}

		}
	}
	
	
	
}
